package com.iemes.controller.inner;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.ClientFormMap;
import com.iemes.entity.ClientRelationFormMap;
import com.iemes.entity.PositionFormMap;
import com.iemes.entity.RoleFormMap;
import com.iemes.entity.UserFormMap;
import com.iemes.entity.UserGroupsFormMap;
import com.iemes.mapper.PositionMapper;
import com.iemes.mapper.ResourcesMapper;
import com.iemes.mapper.RoleMapper;
import com.iemes.mapper.UserGroupsMapper;
import com.iemes.mapper.UserMapper;
import com.iemes.mapper.client.ClientMapper;
import com.iemes.mapper.client.ClientRelationMapper;
import com.iemes.plugin.PageView;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
import com.iemes.util.PasswordHelper;

/**
 * 内部管理
 * 
 * @author 杨飞
 *
 */
@Controller
@RequestMapping("/internalstaff/")
public class InnerController extends BaseController {
	@Inject
	private UserMapper userMapper;
	@Inject
	private ClientMapper clientMapper;
	@Inject 
	private ClientRelationMapper clientRelationMapper;
	@Inject
	private PositionMapper positionMapper;
	@Inject
	private RoleMapper roleMapper;
	@Inject
	private UserGroupsMapper userGroupsMapper;
	@Inject
	private ResourcesMapper resourcesMapper;

	@RequestMapping("userStall")
	public String examineOrder(Model model, HttpServletRequest request) {
		UserFormMap userFormMap = (UserFormMap) Common.findUserSession(request);
		if (!userFormMap.getStr("site").equals("*")) {
			return null;
		}
		// 获取此账号的部门信息
		PositionFormMap positionFormMap = positionMapper.findbyFrist("id",
				userFormMap.get("position_id").toString(),
				PositionFormMap.class);
		List<PositionFormMap> positionFormMaps = positionMapper
				.findByAttribute("departid", positionFormMap.get("departid")
						.toString(), PositionFormMap.class);
		Integer depart=Integer.valueOf(positionFormMap.get("departid").toString());
		
		if(Integer.valueOf(positionFormMap.get("departid").toString())==1){
			List<ClientFormMap> clientFormMaps = clientMapper
					.findByWhere(new ClientFormMap());
			model.addAttribute("client", clientFormMaps);
		}
		model.addAttribute("position", positionFormMaps);
		//判断是否进业务部
		if(depart==1){
			return Common.BACKGROUND_PATH + "/inner/user_userStall";
		}else{
			return Common.BACKGROUND_PATH + "/inner/user_usernoStall";
		}
		
	}

	// 人员信息分页
	@ResponseBody
	@RequestMapping("user_findByPage")
	public PageView findByPage(String pageNow, String pageSize,HttpServletRequest request) throws Exception {
		UserFormMap user = (UserFormMap) Common.findUserSession(request);
		if (!user.getStr("site").equals("*")) {
			return null;
		}
		UserFormMap userFormMap=getFormMap(UserFormMap.class);
		// 获取此账号的部门信息
		PositionFormMap positionFormMap = positionMapper.findbyFrist("id",
				user.get("position_id").toString(),
				PositionFormMap.class);
		List<Map<String, Object>> userFormMaps = new ArrayList<Map<String,Object>>();
		
		if(Integer.valueOf(positionFormMap.get("departid").toString())==1){
			if(userFormMap.get("clientname")!=null){
				userFormMap.put("clientname", "%"+userFormMap.get("clientname").toString()+"%");
			}
			
			 userFormMaps = userMapper.selByClient(userFormMap);
			 for (Map<String, Object> map : userFormMaps) {
				if(map.get("canme")!=null){
					map.put("cname", map.get("canme"));
				}
				if(map.get("clientname")!=null){
					map.put("cname", map.get("clientname"));
				}
			}
		}else{
			userFormMap.put("depart", positionFormMap.get("departid").toString());
			userFormMaps = userMapper.selNoYewu(userFormMap);		
		}
		for (Map<String, Object> map : userFormMaps) {
			if(map.get("site").toString().equals("*")){
				userFormMaps.remove(map);
				break;
			}
		}
		LuogicPaging(pageNow, pageSize, userFormMaps);
		return pageView;
	}

	@RequestMapping("user_add")
	public String User_in(Model model) {
		getPosition(model);
		return Common.BACKGROUND_PATH + "/inner/user_add";

	}

	/**
	 * 验证用户名是否存在
	 * 
	 */
	@RequestMapping("user_isExist")
	@ResponseBody
	public boolean user_isExist(String accountName) {
		List<UserFormMap> account = userMapper.findByAttribute("accountName",
				accountName, UserFormMap.class);
		if (account.size()> 0) {
			return false;
		} else {
			return true;
		}
	}

	// 新增员工
	@ResponseBody
	@RequestMapping("user_addEntity")
	@SystemLog(module = "员工管理", methods = "员工管理-新增用户")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly = false)
	public String addEntity(Model model) {
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		userFormMap.put("password", "123456");
		PasswordHelper passwordHelper = new PasswordHelper();
		passwordHelper.encryptPassword(userFormMap);
		userFormMap.put("createTime", DateUtils.getStringDateTime());
		userFormMap.put("locked", 1);
		userFormMap.put("deletestatus", 0);
		userFormMap.put("site", 0);
		try {
			userMapper.addEntity(userFormMap);
			RoleFormMap roleFormMap=roleMapper.findbyFrist("position_id", userFormMap.get("position_id").toString(), RoleFormMap.class);
			UserGroupsFormMap userGroupsFormMap = getFormMap(UserGroupsFormMap.class);
			userGroupsFormMap.put("userid", userFormMap.get("id"));
			userGroupsFormMap.put("roleid", roleFormMap.get("id"));
			userGroupsMapper.addEntity(userGroupsFormMap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "false";
		}
		return "success";
	}

	// 对用户进行编辑
	@RequestMapping("user_edit")
	public String neworder_edit(Model model) {
		String id = getPara("id");
		// 获取点击的订单
		UserFormMap userFormMap = userMapper.findbyFrist("id", id,
				UserFormMap.class);
		getPosition(model);
		model.addAttribute("userEntity", userFormMap);
		return Common.BACKGROUND_PATH + "/inner/user_edit";
	}

	@ResponseBody
	@RequestMapping("user_editEntity")
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理-修改用户")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity() {
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		try {
			userMapper.editEntity(userFormMap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "false";
		}
		return "success";
	}

	public void getPosition(Model model) {
		// 获取request
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		// 通过工具类获取当前登录的bean
		UserFormMap userFormMap = (UserFormMap) Common.findUserSession(request);
		PositionFormMap position = positionMapper.findbyFrist("id", userFormMap
				.get("position_id").toString(), PositionFormMap.class);
		// 获取部门id,拿到所有岗位
		List<PositionFormMap> positionFormMap = positionMapper
				.getPositionsBydepartid(position.getInt("departid"));
		for (int i = 0; i < positionFormMap.size(); i++) {
			if (positionFormMap.get(i).get("id") == userFormMap
					.get("position_id")) {
				positionFormMap.remove(i);
				break;
			}
		}
		model.addAttribute("position", positionFormMap);
	}
	
	@RequestMapping("client_UI")
	public String client_UI(Model model, HttpServletRequest request) {
		String id = getPara("id");
		if(Common.isNotEmpty(id)){
			model.addAttribute("user", userMapper.findbyFrist("id", id, UserFormMap.class));
		}
		return Common.BACKGROUND_PATH + "/inner/client_relation";
	}
	
	@RequestMapping("selclientRetion")
	public String seletRole(Model model) throws Exception {
		ClientFormMap clientFormMap = getFormMap(ClientFormMap.class);
		Object userId = clientFormMap.get("userId");
		if(null!=userId){
			
			List<Map<String, Object>> list = clientRelationMapper.selByUserid(userId.toString());
			String ugid = "";
			for (Map<String, Object> ml : list) {
				ugid += ml.get("id")+",";
			}
			
			ugid = Common.trimComma(ugid);
			model.addAttribute("txtRoleSelect", ugid);
			model.addAttribute("userRole", list);
			if(StringUtils.isNotBlank(ugid)){
				clientFormMap.put("where", " where id not in ("+ugid+")");
			}
		}
		List<ClientFormMap> clients = clientMapper.findByWhere(clientFormMap);
		model.addAttribute("client", clients);
		return Common.BACKGROUND_PATH + "/inner/clientSelect";
	}
	
	@RequestMapping("Client_relationEntity")
	@ResponseBody
	public String Client_relationEntity(String txtGroupsSelect) throws Exception {
		UserFormMap userFormMap=getFormMap(UserFormMap.class);
		userFormMap=userMapper.findbyFrist("id", userFormMap.get("id").toString(), UserFormMap.class);
		if(!Common.isEmpty(txtGroupsSelect)){
			String[] txt = txtGroupsSelect.split(",");
			
			for (String clientID : txt) {
				//首先判断 客户是否存在
				Integer count = clientRelationMapper.IsExistClient(clientID);
				if(count==0){
					ClientRelationFormMap clientRelationFormMap = getFormMap(ClientRelationFormMap.class);
					Integer position=Integer.valueOf(userFormMap.get("position_id").toString());
					if(position==3){
						clientRelationFormMap.put("salesman_id", userFormMap.get("id").toString());
					}else if (position==2) {
						clientRelationFormMap.put("planner_id", userFormMap.get("id").toString());	
					}else{
						clientRelationFormMap.put("salesman_id", userFormMap.get("id").toString());
					}
					clientRelationFormMap.put("client_id", clientID);
					clientRelationMapper.addEntity(clientRelationFormMap);	
				}else{
					
						ClientRelationFormMap client = getFormMap(ClientRelationFormMap.class);
						client.put("where", " where client_id="+clientID);
						List<ClientRelationFormMap> clients=clientMapper.findByWhere(client);
						Integer position=Integer.valueOf(userFormMap.get("position_id").toString());
						for (ClientRelationFormMap clientRelationFormMap : clients) {
							if(position==3){
								clientRelationFormMap.put("salesman_id", userFormMap.get("id").toString());
							}else if (position==2) {
								clientRelationFormMap.put("planner_id", userFormMap.get("id").toString());	
							}else{
								clientRelationFormMap.put("salesman_id", userFormMap.get("id").toString());
							}
							clientRelationMapper.editEntity(clientRelationFormMap);
						}	
				}
			}
		}
		return "success";
	}
	
}
